|
|
|
|
|
|
|
Writing Code for a Control Array |
|
|
|
|
|
|
|
|
After you create a control array, you can write a single piece of code to handle a particular event for all the controls in the array. For each event, Visual Basic passes the Index property of the control that triggered the event to the event procedure as an argument. This process is illustrated in Figure 13.4. |
|
|
|
|
|
|
|
|
Figure 13.4
Control array event procedures can use the Index parameter
to act according to which element caused the event to occur. |
|
|
|
|
|
|
|
|
Handling the Control Array's Events |
|
|
|
|
|
|
|
|
To write code for each of the elements of a control array, you simply enter the code in the Code window just as you would for any other control. Then, whenever that event is fired by any of the controls in the array, the code is executed. |
|
|
|
|
|
|
|
|
Now you can enhance the sample project with an event procedure. Whenever users complete an entry in any of the three text boxes, you want to convert the text that they typed into proper case (only the first letter of each word is to be capitalized). You can do so by using Visual Basic's StrConv function. |
|
|
|
|
|
|
|
|
But where do you put this code? Controls that can receive the form's focus have a LostFocus event that occurs just before the focus moves from that control to another one. This gives you an excellent opportunity for programmatic validation and formatting of the contents of text boxes. You can add code to the LostFocus event procedure of the text box control array. This code is executed whenever any text box loses the focus, meaning a user has most likely just entered something in the text box. |
|
|
|
|
|
|
|
|
To code the LostFocus event procedure for the test application's text box control array, follow these steps: |
|
|
|
|
|
|
|
|
1. Double-click any of the text boxes that make up the text box control array. The Code window is then displayed, open to the txtArray_Change event procedure. Notice that the parameter Index as Integer is available inside the procedure. |
|
|
|
|
|
|
|
|
2. Because you don't want to write code for the Change event, change the event displayed in the Event drop-down box to LostFocus. |
|
|
|
|
|
|
|
|
3. You should now see the txtArray_LostFocus event procedure, which also has the parameter Index as Integer available. Enter the following line of code into this event procedure: |
|
|
|
|
|
|
|
|
txtArray(Index) = StrConv(txtArray(Index), vbProperCase) |
|
|
|
|
|